const APPID = '6e94975b' //在科大讯飞控制台中获取的服务接口认证信息
/* const API_SECRET = 'MDIzNmI4MzlkYmE5ZDEwYmQwZGU0M2Mx'  *///在科大讯飞控制台中获取的服务接口认证信息
const API_KEY = 'd5cf9b19ba4677429a7089e494eb3121' //在科大讯飞控制台中获取的服务接口认证信息
import CryptoJS from 'crypto-js'
import worker_script from './transcode.js';
// 实时语音转化

const transWorker = new Worker(worker_script)
var startTime = ""
var endTime = ""
function getWebSocketUrl() {
  return new Promise((resolve, reject) => {
    // 请求地址根据语种不同变化
    var url = 'wss://rtasr.xfyun.cn/v1/ws'
    /* var host = 'iat-api.xfyun.cn' */
    var apiKey = API_KEY
    var app_id = APPID;
    var lang = 'cn'
    /* var apiSecret = API_SECRET */
    var ts = Math.floor(+new Date() / 1000)+''
    var baseString = app_id + ts;
    // 首先对数据进行MD5加密
    let md5Result = CryptoJS.MD5(baseString).toString();
    // 使用HmacSHA1加密MD5的结果
    const hmacResult = CryptoJS.HmacSHA1(md5Result, apiKey);
    // 对HmacSHA1的结果进行Base64加密
    const signa = hmacResult.toString(CryptoJS.enc.Base64);
    console.log(signa)
    url = `${url}?appid=${app_id}&ts=${ts}&signa=${encodeURIComponent(signa)}`
    resolve(url)
  })
}
class AsrRecorder {
  /* onStatusChange; */
  onWillStatusChange;
  onWillResultTextTemp;
  constructor({ language, accent, appId, onWillStatusChange,onWillResultTextTemp} = {}) {
    let self = this
    this.status = 'null'
    this.language = language || 'zh_cn'
    this.accent = accent || 'mandarin'
    this.appId = appId || APPID
    // 记录音频数据
    this.audioData = []
    // 记录听写结果
    this.resultText = ''
    // wpgs下的听写结果需要中间状态辅助记录
    this.resultTextTemp = ''
    transWorker.onmessage = function (event) {
      self.audioData.push(...event.data)
    }
    /* this.flag = false */
    /* this.onStatusChange = onStatusChange */
    this.onWillStatusChange = onWillStatusChange;
    this.onWillResultTextTemp = onWillResultTextTemp;
  }
  // 修改录音听写状态
  setStatus(status) {
    this.onWillStatusChange && this.status !== status && this.onWillStatusChange(status, this.status)
    this.status = status
    /* console.log(this.status) */
    /* this.onStatusChange?.(status, this.status) */
  }
  setResultText({ resultText, resultTextTemp } = {}) {
    this.onTextChange && this.onTextChange(resultTextTemp || resultText || '')
    resultText !== undefined && (this.resultText = resultText)
    resultTextTemp !== undefined && (this.resultTextTemp = resultTextTemp)
  }
  // 修改听写参数
  setParams({ language, accent } = {}) {
    language && (this.language = language)
    accent && (this.accent = accent)
  }
  // 连接websocket
  connectWebSocket() {
    return getWebSocketUrl().then(url => {
      let iatWS
      if ('WebSocket' in window) {
        iatWS = new WebSocket(url)
      } else if ('MozWebSocket' in window) {
        iatWS = new MozWebSocket(url)
      } else {
        alert('浏览器不支持WebSocket')
        return
      }
      this.webSocket = iatWS
      this.setStatus('init')
      iatWS.onopen = e => {
        this.setStatus('ing')
        // 重新开始录音
        console.log(this.webSocket)
        
       /*  setTimeout(() => {
          
        }, 500) */
      }
      iatWS.onmessage = e => {
        console.log(e)
        this.result(e.data)
      }
      iatWS.onerror = e => {
        this.recorderStop()
      }
      iatWS.onclose = e => {
        console.log("关闭了")
        this.recorderStop()
      }
    })
  }
  // 初始化浏览器录音
  recorderInit() {
    navigator.getUserMedia =
      navigator.getUserMedia ||
      navigator.webkitGetUserMedia ||
      navigator.mozGetUserMedia ||
      navigator.msGetUserMedia

    // 创建音频环境
    try {
      this.audioContext = new (window.AudioContext || window.webkitAudioContext)()
      this.audioContext.resume()
      if (!this.audioContext) {
        alert('浏览器不支持webAudioApi相关接口')
        return
      }
    } catch (e) {
      if (!this.audioContext) {
        alert('浏览器不支持webAudioApi相关接口')
        return
      }
    }

    // 获取浏览器录音权限
    if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
      navigator.mediaDevices
        .getUserMedia({
          audio: true,
          video: false,
        })
        .then(stream => {
          getMediaSuccess(stream)
        })
        .catch(e => {
          getMediaFail(e)
        })
    } else if (navigator.getUserMedia) {
      navigator.getUserMedia(
        {
          audio: true,
          video: false,
        },
        stream => {
          getMediaSuccess(stream)
        },
        function (e) {
          getMediaFail(e)
        }
      )
    } else {
      if (navigator.userAgent.toLowerCase().match(/chrome/) && location.origin.indexOf('https://') < 0) {
        alert('chrome下获取浏览器录音功能，因为安全性问题，需要在localhost或127.0.0.1或https下才能获取权限')
      } else {
        alert('无法获取浏览器录音功能，请升级浏览器或使用chrome')
      }
      this.audioContext && this.audioContext.close()
      return
    }
    // 获取浏览器录音权限成功的回调
    let getMediaSuccess = stream => {
      console.log('getMediaSuccess')
      // 创建一个用于通过JavaScript直接处理音频
      this.scriptProcessor = this.audioContext.createScriptProcessor(0, 1, 1)
      this.scriptProcessor.onaudioprocess = e => {
        /*  console.log(this) */
        // 去处理音频数据
        if (this.status === 'ing') {
          transWorker.postMessage(e.inputBuffer.getChannelData(0))
        }
      }
      // 创建一个新的MediaStreamAudioSourceNode 对象，使来自MediaStream的音频可以被播放和操作
      this.mediaSource = this.audioContext.createMediaStreamSource(stream)
      // 连接
      this.mediaSource.connect(this.scriptProcessor)
      this.scriptProcessor.connect(this.audioContext.destination)
      this.connectWebSocket()
    }

    let getMediaFail = (e) => {
      alert('请求麦克风失败')
      /* this.onStatusChange('error', '请求麦克风失败') */
      console.log(e)
      this.audioContext && this.audioContext.close()
      this.audioContext = undefined
      // 关闭websocket
      if (this.webSocket && this.webSocket.readyState === 1) {
        this.webSocket.close()
      }
    }
  }
  recorderStart() {
    /* this.recorderInit() */
    if (!this.audioContext) {
      this.recorderInit()
    } else {;
      this.audioContext.resume()
      this.connectWebSocket()
    }
  }
  // 暂停录音
  recorderStop() {
    // safari下suspend后再次resume录音内容将是空白，设置safari下不做suspend
    if (!(/Safari/.test(navigator.userAgent) && !/Chrome/.test(navigator.userAgent))) {
      this.audioContext && this.audioContext.suspend();
      console.log('录音暂停了')
    }
    this.webSocket.send(this.jsonBinary({"end": true}))
    this.setStatus('end');
  }
  // 处理音频数据
  transAudioData(audioData) {
    audioData = transAudioData.transaction(audioData)
    this.audioData.push(...audioData)
  }
  // 对处理后的音频数据进行base64编码，
  toBase64(buffer) {
    var binary = ''
    var bytes = new Uint8Array(buffer)
    var len = bytes.byteLength
    for (var i = 0; i < len; i++) {
      binary += String.fromCharCode(bytes[i])
    }
    return window.btoa(binary)
  }
  int8Array(audioData){
     // 创建一个Uint8Array，因为Int8Array的范围有限(-128~127)，可能会发生溢出
     const uint8Array = new Uint8Array(audioData.map(Number));
     // 获取ArrayBuffer
     const arrayBuffer = uint8Array.buffer;
     return new Int8Array(arrayBuffer)
  }
  jsonBinary(json){
    // 序列化为字符串
    const jsonString = JSON.stringify(json);

    // 创建TextEncoder对象
    const encoder = new TextEncoder();

    // 将字符串编码为ArrayBuffer
    const binaryData = encoder.encode(jsonString);

    // 可以进一步创建为Int8Array
    return new Int8Array(binaryData);
    
  }
  // 向webSocket发送数据
  webSocketSend() {
    console.log(this.webSocket)
    if (this.webSocket.readyState !== 1) {
        return
    }
 
    let audioData = this.audioData.splice(0, 1280)
    console.log(this.audioData)
    /* this.webSocket.send(JSON.stringify(params)) */
      
    
    this.webSocket.send(this.int8Array(audioData)) 
      
    this.handlerInterval = setInterval(() => {
      console.log(this.int8Array(audioData))
      // websocket未连接
      console.log(this.webSocket)
      if (this.webSocket.readyState !== 1) {
        this.audioData = []
        clearInterval(this.handlerInterval)
        return
      }
      if (this.audioData.length === 0) {
        if (this.status === 'end') {
          /* this.webSocket.send(
            JSON.stringify({
              data: {
                status: 2,
                format: 'audio/L16;rate=16000',
                encoding: 'raw',
                audio: '',
              },
            })
          ) */
          this.webSocket.send(this.int8Array(audioData))
          this.audioData = []
          clearInterval(this.handlerInterval)
        }
        return false
      }
      audioData = this.audioData.splice(0, 1280)
      console.log(this.int8Array(audioData))
      // 中间帧
      /* this.webSocket.send(
        JSON.stringify({
          data: {
            status: 1,
            format: 'audio/L16;rate=16000',
            encoding: 'raw',
            audio: this.toBase64(audioData),
          },
        })
      ) */
      this.webSocket.send(this.int8Array(audioData))
    }, 40)
  }
  result(resultData) {
    console.log('识别结束')
    console.log(resultData)
    // 识别结束
    let jsonData = JSON.parse(resultData)
    if (jsonData.data && jsonData.action=='result') {
      console.log('开始翻译')
      let temp = ''
      console.log(JSON.parse(jsonData.data).cn.st.rt[0].ws)
      JSON.parse(jsonData.data).cn.st.rt[0].ws.map((item)=>{
        temp = temp + item.cw[0].w
      })
      this.setResultText({
        resultTextTemp: temp,
      })
      this.setResultText({
        resultText: this.resultTextTemp,
      })
      this.onWillResultTextTemp(this.resultTextTemp)
      console.log(this.resultTextTemp)
    }
    if(jsonData.action=='started'){
        console.log('握手成功')
        this.webSocketSend()
    }
    if (jsonData.code === 'error') {
        this.webSocket.close()
      }
    /* if (jsonData.code === 0 && jsonData.data.status === 2) {
      this.webSocket.close()
    } */
    /* if (jsonData.action == 'started') {
      this.webSocket.close()
      console.log(`${jsonData.code}:${jsonData.message}`)
    } */
  }
  start() {
    this.recorderStart()
    this.setResultText({ resultText: '', resultTextTemp: '' })
  }
  stop() {
    this.recorderStop()
  }
}

export default AsrRecorder
